package auth

import (
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
)

func CreateToken(userName string) (tokenString string) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"iss": "wow-coupon-server",
		"aud": "wow-coupon-server",
		"nbf": time.Now().Unix(),
		"exp": time.Now().Add(10 * time.Minute).Unix(),
		"sub": "user",

		"username": userName,
	})

	tokenString, err := token.SignedString([]byte("verysecretkeyonlyforwowcoupon"))

	if err != nil {
		panic(err)
	}

	return tokenString
}

type Claims struct {
	jwt.StandardClaims
	// Username defines the identity of the user.
	Username string `json:"username"`
}

func CheckToken(tokenString string) (bool, error) {
	var claims Claims
	token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
		if token.Header["alg"] != "HS256" {
			panic("ErrInvalidAlgorithm")
		}
		return []byte("verysecretkeyonlyforwowcoupon"), nil
	})

	if err != nil {
		return false, fmt.Errorf("jwt parse error")
	}

	if !token.Valid {
		return false, fmt.Errorf("ErrInvalidToken")
	}

	return true, nil
	//return claims.Username
}
